﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Diploma.Models;
using Diploma.Validation;

namespace DiplomaWeb.Controllers
{
    [Authorize]
    public class PublicMessagesController : MasterController
    {
        public PublicMessagesController(DataManager dataManager) : base(dataManager)
        {
        }


        public ActionResult Home()
        {
            ViewData["LoggedUser"] = LoggedUser;
            IEnumerable<PublicMessage> portion = DataManager.PublicMessagesRepository.GetPublicMessages(null);
            if (portion != null && portion.Count() != 0)
                ViewData["NextStartMessageId"] = portion.Last().PublicMessageId;
            else
            {
                ViewData["NextStartMessageId"] = null;
            }

            ViewData.Model = portion;
            return PartialView("~/Views/PublicMessages/NewsControl.ascx");
        }


        [HttpGet]
        public ActionResult Add()
        {
            ViewData["LoggedUser"] = LoggedUser;
            return PartialView("~/Views/PublicMessages/PublicMessageAddControl.ascx");
        }

        [HttpPost]
        public JsonResult Add(PublicMessage publicMessage, HttpPostedFileBase postFile)
        {
            ValidationErrors = Validator.ValidatePublicMessage(publicMessage);
            if (ValidationErrors.Count() == 0)
            {
                DataManager.PublicMessagesRepository.Add(publicMessage, postFile);
            }

            return Json(ValidationErrors, "text/plain", JsonRequestBehavior.AllowGet);
        }

        public ActionResult Delete(Guid id)
        {
            PublicMessage message = DataManager.PublicMessagesRepository.GetPublicMessage(id);
            if (message == null || message.UserId != LoggedUser.UserId)
                throw new Exception();
            DataManager.PublicMessagesRepository.Delete(message);

            return null;
        }


        public ActionResult Get(Guid? startMessageId)
        {
            IEnumerable<PublicMessage> nextPortion =
                DataManager.PublicMessagesRepository.GetPublicMessages(startMessageId);
            if (nextPortion != null && nextPortion.Count() != 0)
                ViewData["NextStartMessageId"] = nextPortion.Last().PublicMessageId;
            else
                ViewData["NextStartMessageId"] = null;

            ViewData["LoggedUser"] = LoggedUser;
            ViewData.Model = nextPortion;
            return PartialView("~/Views/PublicMessages/PublicMessagesPortionControl.ascx");
        }
    }
}